<template>
  <div class="operation-log">
    <!-- 搜索表单 -->
    <div class="filter-content">
      <a-form layout="inline" :model="formState">
        <a-form-item label="日期">
          <a-range-picker
            v-model:value="formState.dateRange"
            :disabled-date="disabledDate"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="电站名称">
          <a-select
            v-model:value="formState.stationId"
            placeholder="请选择电站"
            style="width: 200px"
            allowClear
            show-search
            optionFilterProp="label"
            filter-option
          >
            <a-select-option
              v-for="item in stationNameOptions"
              :key="item.stationId"
              :value="item.stationId"
              :label="item.stationName"
            >
              {{ item.stationName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="归属资方：" name="investor">
          <a-select
            ref="select"
            v-model:value="formState.investor"
            style="width: 140px"
            placeholder="请输入搜索"
            show-search
            allowClear
            optionFilterProp="label"
          >
            <a-select-option
              v-for="item in INVESTORS_LIST"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="省份" name="provId">
          <a-select
            ref="select"
            v-model:value="formState.provId"
            class="areaSelect"
            placeholder="省份"
            show-search
            style="width: 140px"
            optionFilterProp="label"
          >
            <a-select-option
              v-for="item in provList"
              :key="item.provId"
              :value="item.provId"
              :label="item.provName"
            >
              {{ item.provName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">查询</a-button>
          <a-button
            style="margin-left: 8px"
            class="greenBtn"
            @click="handleReset"
            >重新计算</a-button
          >
          <!-- <a-tooltip
            placement="right"
            :trigger="'click'"
            v-model:open="resetTooltip"
            @openChange="resetValue"
          >
            <template #title>
              <a-date-picker
                v-model:value="runDate"
                picker="date"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
              />
              <a-button type="link" @click="handleReset" v-if="runDate"
                >确定</a-button
              >
            </template>
            <a-button style="margin-left: 8px" class="greenBtn"
              >重新计算</a-button
            >
          </a-tooltip> -->
          <a-button
            type="primary"
            @click="handleExport"
            style="margin-left: 8px"
            class="yellowBtn"
            >导出</a-button
          >
        </a-form-item>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <div class="tableContent" ref="tableContainerRef">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="false"
        :scroll="tableScroll"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'projectEffi'">
            {{ record.projectEffi ? record.projectEffi + "充" : "" }}
          </template>
          <template v-if="column.dataIndex === 'batteryEffi'">
            {{ record.batteryEffi }}
            <br />
            <ArrowUpOutlined
              style="vertical-align: middle; color: red"
              v-if="record.batteryEffiRatio > 0"
            />
            <ArrowDownOutlined
              style="vertical-align: middle; color: #0bd00f"
              v-else
            />
            <span class="chain">环比：{{ record.batteryEffiRatio }}</span>
          </template>
          <template v-if="column.dataIndex === 'systemEffi'">
            {{ record.systemEffi }}
            <br />
            <ArrowUpOutlined
              style="vertical-align: middle; color: red"
              v-if="record.systemEffiRatio > 0"
            />
            <ArrowDownOutlined
              style="vertical-align: middle; color: #0bd00f"
              v-else
            />
            <span class="chain">环比：{{ record.systemEffiRatio }}</span>
          </template>
          <template v-if="column.dataIndex === 'airQuan'">
            {{ record.airQuan }}
            <br />
            <ArrowUpOutlined
              style="vertical-align: middle; color: red"
              v-if="record.airQuanRatio > 0"
            />
            <ArrowDownOutlined
              style="vertical-align: middle; color: #0bd00f"
              v-else
            />
            <span class="chain">环比：{{ record.airQuanRatio }}</span>
          </template>
          <template v-if="column.dataIndex === 'tempMax'">
            <a-tooltip
              :title="`${record.tempMaxLinkName}`"
              :color="'blue'"
              placement="right"
            >
              {{ record.tempMax }}
            </a-tooltip>

            <br />
            <ArrowUpOutlined
              style="vertical-align: middle; color: red"
              v-if="record.tempMaxRatio > 0"
            />
            <ArrowDownOutlined
              style="vertical-align: middle; color: #0bd00f"
              v-else
            />
            <span class="chain">环比：{{ record.tempMaxRatio }}</span>
          </template>
          <template v-if="column.dataIndex === 'maxVoltDiff'">
            {{ record.maxVoltDiff }}
            <br />
            <ArrowUpOutlined
              style="vertical-align: middle; color: red"
              v-if="record.maxVoltDiffRatio > 0"
            />
            <ArrowDownOutlined
              style="vertical-align: middle; color: #0bd00f"
              v-else
            />
            <span class="chain">环比：{{ record.maxVoltDiffRatio }}</span>
          </template>
          <template v-if="column.dataIndex === 'handle'">
            <a-button
              type="link"
              @click="checkDetial(record)"
              :disabled="!record.projectEffiDetail"
              >详情</a-button
            >
          </template>
        </template>
      </a-table>
    </div>

    <!-- 添加计算详情弹窗 -->
    <a-modal
      v-model:open="detailVisible"
      title="全周期利用情况计算详情"
      :footer="null"
      width="60%"
    >
      <div class="formula-detail">
        <div class="formula-item">
          <div class="title">
            公式：<span class="content">
              全周期利用情况 = (累计充电量-空调耗电量) /
              (装机容量*1000*运行日天数)
            </span>
          </div>
        </div>
        <div class="formula-item">
          <div class="title">
            属性名称计算公式：
            <span class="content">
              全周期利用情况 = (station_day_input_kwh - station_air_quan) /
              (station_cap*1000*运行日天数)
            </span>
          </div>
        </div>
        <div class="formula-item">
          <div class="title">
            值计算：<span class="content"> {{ detailData }} </span>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>

import dayjs from "dayjs"
import { INVESTORS_LIST } from "@/constants/stationConfig"
import utilsExportFile from "@/utils/exportFile"
import useTableScroll from "@/hooks/useTableScroll"
const total = ref(0)
const $api = inject("$api")
//获取省份列表
const provList = ref([])
const getBaseProvinceTree = async () => {
  const res = await $api.baseProvinceTree()
  provList.value = res.data
}
// 表单状态
const yesterday = dayjs().subtract(1, "day").format("YYYY-MM-DD")
const formState = reactive({
  dateRange: [yesterday, yesterday],
  stationId: undefined,
  current: 1,
  size: 10,
})

// 表格列定义
const columns = [
  {
    title: "运行日",
    dataIndex: "runDateStr",
    key: "runDateStr",
    align: "center",
    width: 120,
  },
  {
    title: "电站名称",
    dataIndex: "stationName",
    key: "stationName",
    align: "center",
    width: 150,
  },
  {
    title: "全周期项目利用情况",
    dataIndex: "projectEffi",
    key: "projectEffi",
    align: "center",
    width: 100,
  },
  {
    title: "电池充放电效率",
    dataIndex: "batteryEffi",
    key: "batteryEffi",
    align: "center",
    width: 120,
  },
  {
    title: "系统运行效率",
    dataIndex: "systemEffi",
    key: "systemEffi",
    align: "center",
    width: 120,
  },
  {
    title: "空调耗电量",
    dataIndex: "airQuan",
    key: "airQuan",
    align: "center",
    width: 120,
  },
  {
    title: "电芯最高温度（℃）",
    dataIndex: "tempMax",
    key: "tempMax",
    align: "center",
    width: 120,
  },

  {
    title: "电芯最大压差",
    dataIndex: "maxVoltDiff",
    key: "maxVoltDiff",
    align: "center",
    width: 120,
  },
  {
    title: "离线比",
    dataIndex: "offlineRate",
    key: "offlineRate",
    align: "center",
    width: 120,
  },
  {
    title: "故障累计损失电量（kWh）",
    dataIndex: "badQuan",
    key: "badQuan",
    align: "center",
    width: 120,
  },
  {
    title: "SOH",
    dataIndex: "soh",
    key: "soh",
    align: "center",
    width: 120,
  },
  {
    title: "操作",
    dataIndex: "handle",
    key: "handle",
    align: "center",
    width: 60,
  },
]

// 数据状态
const loading = ref(false)
const tableData = ref([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
})

//获取电站列表
const stationNameOptions = ref([])
const handleSearchStationName = async () => {
  const res = await $api.companyStationtList()
  stationNameOptions.value = res.data
  await nextTick()
}

// 方法定义
const handleSearch = async () => {
  formState.current = 1
  getList()
}
const getList = async () => {
  loading.value = true
  try {
    // 这里添加实际的API调用
    const params = {
      runStartDate:
        formState.dateRange && formState.dateRange.length > 0
          ? formState.dateRange[0]
          : null,
      runEndDate:
        formState.dateRange && formState.dateRange.length > 0
          ? formState.dateRange[1]
          : null,
      ...formState,
    }
    const res = await $api.stationRunLogList(params)
    tableData.value = res.data
    //total.value = res.data.total
  } catch (error) {
    message.error("获取数据失败")
  } finally {
    loading.value = false
  }
}
const handleExport = async () => {
  const params = {
    runStartDate: formState.dateRange[0],
    runEndDate: formState.dateRange[1],
    ...formState,
  }
  const res = await $api.stationRunLogExportData(params)
  utilsExportFile.exportFile(
    res,
    `${params.runStartDate}-${params.runEndDate}运行日志.xlsx`
  )
}
const runDate = ref(null)
const resetTooltip = ref(false)
const handleReset = async () => {
  if (!formState.dateRange || formState.dateRange.length === 0) {
    message.error("请选择计算日期")
    return
  } else if (
    formState.dateRange &&
    formState.dateRange.length > 0 &&
    formState.dateRange[0] !== formState.dateRange[1]
  ) {
    message.error("开始时间和结束时间请选择相同日期")
    return
  }
  const res = await $api.repeatCompute({
    runStartDate: formState.dateRange[0],
    repeatStationIdList: formState.stationId ? [formState.stationId] : [],
  })
  if (res && res.code === 0) {
    message.success("操作成功")
    resetTooltip.value = false
  }
  handleSearch()
}
const resetValue = () => {
  runDate.value = null
}

const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  handleSearch()
}

const handlePreview = (record) => {
  previewImage.value = record.imageUrl
  previewVisible.value = true
}

const handleCancel = () => {
  previewVisible.value = false
}

const disabledDate = (current) => {
  return current && current > dayjs().endOf("day")
}

onMounted(() => {
  getBaseProvinceTree()
  handleSearch()
  handleSearchStationName()
})

// 详情弹窗相关
const detailVisible = ref(false)
const detailData = ref("")

// 查看详情方法
const checkDetial = async (record) => {
  console.log(record)
  try {
    detailData.value = record.projectEffiDetail
    detailVisible.value = true
  } catch (error) {
    console.log(error)
    message.error("获取详情数据失败")
  }
}
const tableContainerRef = ref(null)
const { tableScroll } = useTableScroll(tableData, tableContainerRef, 100)
</script>

<style lang="less" scoped>
.operation-log {
  .filter-content {
    background: #141414;
    padding: 24px;
    border-radius: 4px;
    margin-bottom: 24px;
  }

  :deep(.ant-table) {
    background: #141414;
  }

  :deep(.ant-pagination) {
    margin-top: 16px;
    text-align: right;
  }
}

.formula-detail {
  margin-top: 20px;
  .formula-item {
    margin-bottom: 20px;

    .title {
      font-weight: bold;
      margin-bottom: 8px;
      color: #1890ff;
    }

    .content {
      line-height: 1.5;
      color: #fff;
    }
  }
}
.tableContent {
  border-radius: 4px;
  background-color: #141414;
  padding: 8px;
}
</style>
